# -*- encoding:utf-8 -*-
# @Time : 2020/12/21 10:08
# @Author : ZHH
"""
通过Python编程完成一个银行ATM机模拟系统，具备如下功能:
(1)登陆验证：用户输入用户名密码登陆，检测用户名是否存在以及用户名密码是否匹配；用户名密码共有三次输入机会，超过三次系统退出。
(2)菜单界面：登陆成功后显示功能操作界面，输入序号选择对应功能。
(3)用户注册：用户可以输入用户名和密码创建自己的账号，并输入电话号码等信息，如果用户名存在则让用户重新输入用户名。注册后免费赠送5000元余额。
(4)账户管理：用户可以随时查看自己的账户余额。用户可以输入其他账户用户名，实现转账功能；转账时用户名必须存在，否则提示异常。用户也可以模拟实现存取款功能。
(5)用户名和密码以及账户信息等必须永久保存。且基于命令行完成，不需要开发GUI界面。
"""

import sqlite3
import datetime


class SQLExecute:
    def __init__(self, filename):
        self.__filename = filename
        self.__conn = sqlite3.connect(self.__filename)

    def _init_table(self):
        delete_ = 'drop table if exists user_info;'
        self.__conn.execute(delete_)
        add_ = 'create table user_info (id integer primary key , username varchar (255) , password varchar (255),phone int, money int );'
        self.__conn.execute(add_)
        index_ = "create unique index username on user_info ('username')"
        self.__conn.execute(index_)

    def insert_data(self, name, password, phone, money):
        sql = f"insert into user_info (id,username,password,phone,money)values (NULL ,'{name}','{password}','{phone}','{money}') "
        self.__conn.execute(sql)
        self.__conn.commit()

    def update_data(self, key, value, name):
        update_ = f'update user_info set {key} = {value} where  username="{name}"'
        self.__conn.execute(update_)
        self.__conn.commit()

    def select_data(self, key, name, password=None):
        if password:
            sql = f"""select {key} from user_info where username = "{name}" and password = "{password}" """
        else:
            sql = f"""select {key} from user_info where username = "{name}" """
        result = self.__conn.execute(sql)
        result = result.fetchone()
        return result


class ATM:
    __split = '-' * 30

    def __init__(self, sql_path):
        self.__sql_ = SQLExecute(sql_path)
        print('ATM初始化成功')

    def start_menu(self):
        while True:
            print("-----------欢迎使用-----------")
            print("1、已拥有账户，直接登录\n2、注册帐号\n3、退出系统")
            user_input = input('请输入按键：')
            if user_input not in {'1', '2', '3'}:
                print('输入错误，请重新输入')
            elif int(user_input) == 1:
                self.login()
                break
            elif int(user_input) == 2:
                self.register()
                break
            else:
                self.exit()
                break

    def exit(self):
        print(self.__split)
        print('感谢使用')

    def login(self):
        count = 0
        while True:
            print(self.__split)
            username = input('请输入用户名：')
            password = input('请输入密码：')
            result = self.__sql_.select_data('*', username, password)
            if result:
                self.menu(username)
                break
            else:
                count += 1
                if count == 3:
                    print('输入帐号或密码错误次数过多,请稍后再试')
                    break
                print("帐号或密码错误，请重新输入")

    def register(self):
        while True:
            print(self.__split)
            username = input('请输入用户名：')
            password = input('请输入密码：')
            phone = input('请输入手机号码：')
            result = self.__sql_.select_data('username', username)
            if result:
                print(f'用户名{username}，已存在，请重新输入')
                continue
            print(self.__split)
            s = input(f'您注册的帐号为：{username}，密码：{password}，手机号：{phone}\n1、确认注册\n2、返回首页\n请输入选项：')
            if s == '1':
                self.__sql_.insert_data(username, password, phone, 5000)
                print('注册成功，自动登录')
                self.menu(username)
                break
            else:
                self.start_menu()
                break

    def menu(self, username):
        while True:
            now = str(datetime.datetime.now())[:-7]
            print(self.__split)
            print(f'{username} 先生/女士 您好\n{now}')
            print(self.__split)
            print('1、查询余额\n2、转账\n3、存款\n4、取款\n5、退出')
            user_input = input('请输入按键：')
            if user_input not in {'1', '2', '3','4','5'}:
                print('输入错误，请重新输入')
            elif int(user_input) == 1:
                self.view_info(username)
                break
            elif int(user_input) == 2:
                self.transfer(username)
                break
            elif int(user_input) == 3:
                self.save_money(username)
                break
            elif int(user_input) == 4:
                self.get_money(username)
                break
            else:
                self.exit()
                break

    def get_money(self, username):
        while True:
            try:
                print(self.__split)
                money = int(input('请输入金额：'))
                old_result = self.__sql_.select_data('money', username)
                if money > old_result[0]:
                    print(f'账户余额不足，账户余额：{old_result[0]}，请重新输入金额')
                    continue
                self.__sql_.update_data('money', f'money-{money}', username)
                result = self.__sql_.select_data('money', username)
                print(f'已成功取出{money}元，账户余额{result[0]}元')
                input('输入任意键返回：')
                self.menu(username)
                break
            except ValueError:
                print('输入金额格式错误，请重新输入')
                continue

    def save_money(self, username):
        while True:
            try:
                print(self.__split)
                money = int(input('请输入金额：'))
                self.__sql_.update_data('money', f'money+{money}', username)
                result = self.__sql_.select_data('money', username)
                print(f'已成功存入{money}元，账户余额{result[0]}元')
                input('输入任意键返回：')
                self.menu(username)
                break
            except ValueError:
                print('输入金额格式错误，请重新输入')
                continue

    def view_info(self, username):
        result = self.__sql_.select_data('money', username)
        print(self.__split)
        print(f"您的余额：{result[0]}")
        input('输入任意键返回上级菜单：')
        self.menu(username)

    def transfer(self, username):
        while True:
            print(self.__split)
            user = input('请输入对方用户名：')
            result = self.__sql_.select_data('money', user)
            if not result:
                input('用户名不存在，输入任意键返回主菜单：')
                self.menu(username)
                break
            else:
                try:
                    money = int(input('请输入转账金额：'))
                except ValueError:
                    print('输入金额格式错误')
                    continue
                my_money = self.__sql_.select_data('money', username)[0]
                if money > my_money:
                    print('余额不足')
                    self.menu(username)
                    break
                else:
                    s = input(f'是否确定转账给{user}？\n1、确认\n2、取消')
                    if s == '1':
                        self.__sql_.update_data('money', my_money - money, username)
                        self.__sql_.update_data('money', result[0] + money, user)
                        print('转账成功')
                        s = input('返回菜单请按1，输入其他任意键退出：')
                        if s == '1':
                            self.menu(username)
                            break
                        self.exit()
                        break
                    else:
                        self.menu(username)
                        break


# SQLExecute('user_p022.db')._init_table()
ATM('user_p022.db').start_menu()
# 厉害了亲，sql的语句都用上了